/* *
 * ---------------------------------------- *
 * 区县选择组件 v1.0
 * ---------------------------------------- *
 * */

/**
 * input:   		选择区县的输入框id
 * idTT：           选择区县保存ID值
 * parentId:        父级Id,若为空，则显示所有数据
 * boxId:		弹出框ID
 * isLowerLevel：	是否调用下一级，'yes'调用，no或''不调用
 * lowerData：		下一级参数数据，当isLowerLevel为yes时，须传参数数据
 */
//<input type="text" id="areaId" name="areaId" value=""/>
//<input type="text" class="addressinput" id="areaTT" value="区县"/>
//new AddressArea.addressSelector({input:'areaTT', idTT:'areaId', parentId:1, boxId: 'areaDiv'});
//new AddressArea.addressSelector({input:'areaTT', idTT:'areaId', parentId:1, boxId: 'areaDiv', isLowerLevel：'no'});
//new AddressArea.addressSelector({input:'areaTT', idTT:'areaId', parentId:1, boxId: 'areaDiv', isLowerLevel：'yes', lowerData:'下一级参数数据'});

var AddressArea = {};

AddressArea.areaDatas = {};
AddressArea.oaddress = {};

/**
 * 从后台获取下级数据
 */
AddressArea.getAddressData = function(argsData){
	$.ajax({
		url : '/service/address/data/area/'+argsData.countyCode+'/'+argsData.langCode,
		data:{
				parentId: encodeURI(argsData.parentId)
			},
		type : 'get',
        dataType:'json',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
		success : function(data) {
			//set data
			AddressArea.areaDatas[argsData.boxId] = {};
			AddressArea.areaDatas[argsData.boxId].addressData = data.areaData;
			
			AddressArea.oaddress[argsData.boxId] = {address:{}};
			
			var addresss = AddressArea.areaDatas[argsData.boxId];
		    var n = addresss.addressData.length;
		    for (var i = 0; i < n; i++) {
		    	if(/^[\u4e00-\u9fa5]+$/i.test(addresss.addressData[i].parentName)){
		    		var letter = 'ZZ';
		    		if(addresss.addressData[i].abb){
		    			letter=addresss.addressData[i].abb.substring(0,2).toUpperCase();
		    		}
		    		//名字－id－父id
		    		var match = addresss.addressData[i].name + "^" + addresss.addressData[i].id + "^" + addresss.addressData[i].parentId;
		    		if (!AddressArea.oaddress[argsData.boxId].address[letter]) 
		    			AddressArea.oaddress[argsData.boxId].address[letter] = [];
		    		AddressArea.oaddress[argsData.boxId].address[letter].push(match);
		    	}else{
		    		var letter = 'ZZ';
		    	/*	if(addresss.addressData[i].abb){
		    			letter=addresss.addressData[i].abb.substring(0,2).toUpperCase();
		    		}*/
		    		//名字－id－父id
		    		var match = addresss.addressData[i].name + "^" + addresss.addressData[i].id + "^" + addresss.addressData[i].parentId;
		    		if (!AddressArea.oaddress[argsData.boxId].address[letter]) 
		    			AddressArea.oaddress[argsData.boxId].address[letter] = [];
		    		AddressArea.oaddress[argsData.boxId].address[letter].push(match);
		    	}
		    }
			
		    //设置数据
	        //argsData.areaDatas = areaDatas;
	        //argsData.oaddress = oaddress;
			new AddressArea.addressSelector(argsData);
		},
		error : function() {
			sfAlert('后台获取区县数据失败，请重新获取');
		}
	});
};

/* *
 * 静态方法集
 * @name _m
 * */
AddressArea._m = {
    /* 选择元素 */
    $:function (arg, context) {
        var tagAll, n, eles = [], i, sub = arg.substring(1);
        context = context || document;
        if (typeof arg == 'string') {
            switch (arg.charAt(0)) {
                case '#':
                    return document.getElementById(sub);
                    break;
                case '.':
                    if (context.getElementsByClassName) return context.getElementsByClassName(sub);
                    tagAll = AddressArea._m.$('*', context);
                    n = tagAll.length;
                    for (i = 0; i < n; i++) {
                        if (tagAll[i].className.indexOf(sub) > -1) eles.push(tagAll[i]);
                    }
                    return eles;
                    break;
                default:
                    return context.getElementsByTagName(arg);
                    break;
            }
        }
    },

    /* 绑定事件 */
    on:function (node, type, handler) {
        node.addEventListener ? node.addEventListener(type, handler, false) : node.attachEvent('on' + type, handler);
    },

    /* 获取事件 */
    getEvent:function(event){
        return event || window.event;
    },

    /* 获取事件目标 */
    getTarget:function(event){
        return event.target || event.srcElement;
    },

    /* 获取元素位置 */
    getPos:function (node) {
        var scrollx = document.documentElement.scrollLeft || document.body.scrollLeft,
                scrollt = document.documentElement.scrollTop || document.body.scrollTop;
        var pos = node.getBoundingClientRect();
        return {top:pos.top + scrollt, right:pos.right + scrollx, bottom:pos.bottom + scrollt, left:pos.left + scrollx };
    },

    /* 添加样式名 */
    addClass:function (c, node) {
        if(!node)return;
        node.className = AddressArea._m.hasClass(c,node) ? node.className : node.className + ' ' + c ;
    },

    /* 移除样式名 */
    removeClass:function (c, node) {
        var reg = new RegExp("(^|\\s+)" + c + "(\\s+|$)", "g");
        if(!AddressArea._m.hasClass(c,node))return;
        node.className = reg.test(node.className) ? node.className.replace(reg, '') : node.className;
    },

    /* 是否含有CLASS */
    hasClass:function (c, node) {
        if(!node || !node.className)return false;
        return node.className.indexOf(c)>-1;
    },

    /* 阻止冒泡 */
    stopPropagation:function (event) {
        event = event || window.event;
        event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
    },
    
    /* 去除两端空格 */
    trim:function (str) {
        return str.replace(/^\s+|\s+$/g,'');
    }
};

/* 正则表达式 筛选中文地点名、拼音、首字母 */
AddressArea.regEx = /^([\u4E00-\u9FA5\uf900-\ufa2d]+)\|(\w+)\|(\w)\w*$/i;
AddressArea.regExChiese = /([\u4E00-\u9FA5\uf900-\ufa2d]+)/;

/* 地点HTML模板 */
AddressArea._template = [
];

/* *
 * 地点控件构造函数
 * @addressSelector
 * */
AddressArea.addressSelector = function () {
    this.initialize.apply(this, arguments);
};

/**
 * 删除已创建area div
 */
AddressArea.removeBox = function(boxId){
	var areaBox = document.getElementById(boxId);
	if(areaBox != null){
		document.body.removeChild(areaBox);
	}
};

AddressArea.addressSelector.prototype = {
    constructor:AddressArea.addressSelector,

    /* 初始化 */
    initialize :function (options) {
    	//box div id
    	this.boxId = options.boxId;
    	
    	AddressArea.removeBox(this.boxId);
    	
    	//set input
    	var input = options.input;
        this.input = AddressArea._m.$('#'+ input);
        
        //地点id
        var idTT = options.idTT;
        this.addressId = AddressArea._m.$('#'+ idTT);
        
        //获取上级ID
        this.parentId = options.parentId;

        //设置区域变更函数	
        this.changeAreaFunc = options.changeAreaFunc;
        
        //创建box
        this.inputEvent();
        
        this.parentInput = AddressHelper.isEmpty(options.parentInput) ? "" : options.parentInput;
        
        //设置input值
        if(this.setInput()){
        	return ;
        }
        
        //当只有父级id不为空且id为空时直接弹出地址
        if(options.parentId != null && options.parentId != ''){
        	//设置直接弹出下一级
        	this.createWarp();
        }
    },
    
    
    /**
     * 关闭显示
     */
    closeAdress:function(){
    	var that = this;
    	AddressArea._m.addClass('hide',that.addressBox);
    	/* 点击地点名的时候隐藏myIframe */
    	AddressArea._m.addClass('hide',that.myIframe);
    },

    /**
     * 设置input值
     */
    setInput:function(){
    	var that = this;
    	var idVal = that.addressId.value;
    	if(idVal != null && idVal != ''){
    		var areaData = AddressArea.areaDatas[that.boxId].addressData;
            var n = areaData.length;
            for (var i = 0; i < n; i++) {
            	if(areaData[i].id == idVal){
            		that.input.value = areaData[i].name;
            		break;
            	}
            }
            
            //区域值变更调用
            if(!AddressHelper.isEmpty(that.changeAreaFunc) && !AddressHelper.isEmpty(idVal)){
            	that.changeAreaFunc.call(this,idVal);
            }
            
            return true;
    	}
    	
    	return false;
    },
    
    /* *
     * @createWarp
     * 创建地点BOX HTML 框架
     * */
    createWarp:function(){
    	var that = this;
    	var div = document.getElementById(that.boxId);
        if(div == null){
        	var inputPos = AddressArea._m.getPos(that.input);
        	div = this.rootDiv = document.createElement('div');
        	
        	// 设置DIV阻止冒泡
        	AddressArea._m.on(this.rootDiv,'click',function(event){
        		AddressArea._m.stopPropagation(event);
        	});
        	
        	// 设置点击文档隐藏弹出的地点选择框
        	AddressArea._m.on(document, 'click', function (event) {
        		event = AddressArea._m.getEvent(event);
        		var target = AddressArea._m.getTarget(event);
        		if(target == that.input) 
        			return false;
        		if (that.addressBox)
        			AddressArea._m.addClass('hide', that.addressBox);
        		if (that.ul)
        			AddressArea._m.addClass('hide', that.ul);
        		if(that.myIframe)
        			AddressArea._m.addClass('hide',that.myIframe);
        	});
        	div.className = 'addressSelector';
        	div.id = that.boxId;
        	div.style.position = 'absolute';
        	div.style.left = inputPos.left + 'px';
        	div.style.top = inputPos.bottom + 'px';
        	div.style.zIndex = 999999;
        	
        	// 判断是否IE6，如果是IE6需要添加iframe才能遮住SELECT框
        	var isIe = (document.all) ? true : false;
        	var isIE6 = this.isIE6 = isIe && !window.XMLHttpRequest;
        	if(isIE6){
        		var myIframe = this.myIframe =  document.createElement('iframe');
        		myIframe.frameborder = '0';
        		myIframe.src = 'about:blank';
        		myIframe.style.position = 'absolute';
        		myIframe.style.zIndex = '-1';
        		this.rootDiv.appendChild(this.myIframe);
        	}
        	
        	var childdiv = this.addressBox = document.createElement('div');
        	childdiv.className = 'addressBox';
        	childdiv.id = 'addressBox';
        	childdiv.innerHTML = AddressCity._template.join('');
        	div.appendChild(childdiv);
        }
        this.createAddress();
    },
    
    isChineseWord:function (str){
      	 var reg = /^[\u4e00-\u9fa5]+$/i; 
      	 var flag=false;
      	 for(var i=0;i<str.length;i++){
      		 if (reg.test(str.substring(i,i+1))) 
      		 {
      		   flag= true;
      		   break;
      		 }
      	 }
      	 return flag;
      },

    /* *
     * @createAddress
     * TAB下面DIV：a-h,i-p,q-z 分类HTML生成，DOM操作
     * {ABCDEFGH:{a:[1,2,3],b:[1,2,3]},IJKLMNOP:{},QRSTUVWXYZ:{}}
     **/
    createAddress:function(){
    	if(!this.addressBox) {
            this.addressBox = document.createElement('div');
        }
        if(!this.rootDiv) {
            this.rootDiv = document.createElement('div');
        }
        var oaddress = AddressArea.oaddress[this.boxId];
        for(var key in oaddress){
        	var oul = document.createElement('ul');
           	oul.className = 'clearfix addctiy_list';
            
            var sortKey=[];
            var sortKeyAll=[];
            for(var ckey in oaddress[key]){
            	if(/^\d+$/.test(ckey)){
            		sortKey.push(ckey);
            		// ckey按照ABCDEDG顺序排序
            		sortKey.sort();
            	}else{
            		var n=oaddress[key][ckey].length;
            		for(var i=0; i<n; i++){
            			//名字－id－父id
            			var tmp = oaddress[key][ckey][i];
            			sortKeyAll.push(tmp);
            		}
            		if(!this.isChineseWord(sortKeyAll[0].split('^')[0])){
            			oaddress[key][ckey].sort();
            		}
            	}
            	
            }
            
            var k=sortKeyAll.length;
            for(var j=0; j<k ;j++){
        
            	//名字－id－父id
            	var tmp = sortKeyAll[j].split('^');
    			var str = '<a href="javascript:void(0);" name="' + tmp[1] + '" >' + tmp[0] + '</a>';
    			
    			var oli = document.createElement('li');
        		oli.innerHTML = str;
        		oul.appendChild(oli);
             
            }
            var kk = sortKey.length;
            for(var j=0; j<kk ;j++){
            	var n=oaddress[key][sortKey[j]].length;
                for(var i=0; i<n; i++){
                	//名字－id－父id
                	var tmp = oaddress[key][sortKey[j]][i].split('^');
        			var str = '<a href="javascript:void(0);" name="' + tmp[1] + '" >' + tmp[0] + '</a>';
        			
        			var oli = document.createElement('li');
            		oli.innerHTML = str;
            		oul.appendChild(oli);
                }
            }
            this.addressBox.appendChild(oul);
        }
        document.body.appendChild(this.rootDiv);
        /* IE6 */
        this.changeIframe();

        this.linkEvent();
    },

    /* *
     * 地点LINK事件
     *  @linkEvent
     * */
    linkEvent:function(){
        var links = AddressArea._m.$('a',this.addressBox);
        var that = this;
        for(var i=0,n=links.length;i<n;i++){
            links[i].onclick = function(){
            	that.closeAdress();
            	
            	//设置input
            	that.input.value = this.innerHTML;
            	
            	//获地点ID
            	that.addressId.value = this.name;
                
                //区域值变更调用
                if(!AddressHelper.isEmpty(that.changeAreaFunc)){
                	that.changeAreaFunc.call(this,that.addressId.value);
                }
            	return false;
            };
        }
    },

    /* *
     * INPUT地点输入框事件
     * @inputEvent
     * */
    inputEvent:function(){
        var that = this;
        AddressArea._m.on(this.input,'click',function(event){
        	//如果input没有值，则不弹框
            if(AddressHelper.isEmpty(that.parentInput.value) 
            		|| that.parentInput.value == AddressHelper.CITY_NULL_NAME){
            	return;
            }
        	
            event = event || window.event;
            if(!that.addressBox){
                that.createWarp();
            }else if(!!that.addressBox && AddressArea._m.hasClass('hide',that.addressBox)){
                // slideul 不存在或者 slideul存在但是是隐藏的时候 两者不能共存
                if(!that.ul || (that.ul && AddressArea._m.hasClass('hide',that.ul))){
                    AddressArea._m.removeClass('hide',that.addressBox);

                    /* IE6 移除iframe 的hide 样式 */
                    AddressArea._m.removeClass('hide',that.myIframe);
                    that.changeIframe();
                }
            }
        });
        AddressArea._m.on(this.input,'focus',function(){
        	that.closeAdress();
            that.input.select();
        });
        AddressArea._m.on(this.input,'blur',function(){
        });
        AddressArea._m.on(this.input,'keyup',function(event){
            event = event || window.event;
            var keycode = event.keyCode;
            AddressArea._m.addClass('hide',that.addressBox);
            that.createUl();

            /* 移除iframe 的hide 样式 */
            AddressArea._m.removeClass('hide',that.myIframe);

            // 下拉菜单显示的时候捕捉按键事件
            if(that.ul && !AddressArea._m.hasClass('hide',that.ul) && !that.isEmpty){
                that.KeyboardEvent(event,keycode);
            }
        });
        AddressArea._m.on(this.input,'keydown',function(event){
            event = event || window.event;
            var keycode = event.keyCode;
            if(keycode == 9){
            	that.closeAdress();
            }
        });
    },

    /* *
     * 生成下拉选择列表
     * @ createUl
     * */
    createUl:function () {
        var val = AddressArea._m.trim(this.input.value);
        var len = val.length;
        //TODO
        //var addresss = AddressArea.datas;
        //var addresss = this.areaDatas;
        var addresss = AddressArea.areaDatas[this.boxId];
        // 当val不等于空的时候执行
        if (val !== '') {
            // 此处需设置中文输入法也可用onpropertychange
            var searchResult = [];
            var n = addresss.addressData.length;
            for (var i = 0; i < n; i++) {
        		//搜索只要跟中文和拼音一样，则显示
				if(addresss.addressData[i].abb){
	            	if(val == addresss.addressData[i].abb.substring(0,len) || val == addresss.addressData[i].spell.substring(0,len) || val == addresss.addressData[i].name.substring(0,len)){
	            		var str = '<li';
	            		if (searchResult.length == 0) {
	            			str += ' class="on"';
	                    } 
	            		str += '><b  name="' + addresss.addressData[i].id;
	            		str += '" class="addressname">' + addresss.addressData[i].name + '</b>';
	            		str += '<b class="addressspell">' + addresss.addressData[i].abb + '</b>';
	            		str += '<b class="addressspell">' + addresss.addressData[i].spell + '----</b>';
	            		str += '</li>';
	            		
	            		searchResult.push(str);
	            	}
				}
            }
            this.isEmpty = false;
            // 如果搜索数据为空
            if (searchResult.length == 0) {
                this.isEmpty = true;
                str = '<li class="empty">对不起，没有找到数据 "<em>' + val + '</em>"</li>';
                
                //id为空
                this.addressId.value = "";
                
                searchResult.push(str);
            }
            // 如果slideul不存在则添加ul
            if (!this.ul) {
                var ul = this.ul = document.createElement('ul');
                ul.className = 'addressslide';
                this.rootDiv && this.rootDiv.appendChild(ul);
                // 记录按键次数，方向键
                this.count = 0;
            } else if (this.ul && AddressArea._m.hasClass('hide', this.ul)) {
                this.count = 0;
                AddressArea._m.removeClass('hide', this.ul);
            }
            this.ul.innerHTML = searchResult.join('');

            /* IE6 */
            this.changeIframe();

            // 绑定Li事件
            this.liEvent();
        }else{
            AddressArea._m.addClass('hide',this.ul);
            AddressArea._m.removeClass('hide',this.addressBox);
            AddressArea._m.removeClass('hide',this.myIframe);

            this.changeIframe();
        }
    },

    /* IE6的改变遮罩SELECT 的 IFRAME尺寸大小 */
    changeIframe:function(){
        if(!this.isIE6)return;
        this.myIframe.style.width = this.rootDiv.offsetWidth + 'px';
        this.myIframe.style.height = this.rootDiv.offsetHeight + 'px';
    },

    /* *
     * 特定键盘事件，上、下、Enter键
     * @ KeyboardEvent
     * */
    KeyboardEvent:function(event,keycode){
        var lis = AddressArea._m.$('li',this.ul);
        var len = lis.length;
        switch(keycode){
            case 40: //向下箭头↓
                this.count++;
                if(this.count > len-1) this.count = 0;
                for(var i=0;i<len;i++){
                    AddressArea._m.removeClass('on',lis[i]);
                }
                AddressArea._m.addClass('on',lis[this.count]);
                break;
            case 38: //向上箭头↑
                this.count--;
                if(this.count<0) this.count = len-1;
                for(i=0;i<len;i++){
                    AddressArea._m.removeClass('on',lis[i]);
                }
                AddressArea._m.addClass('on',lis[this.count]);
                break;
            case 13: // enter键
                this.input.value = AddressArea.regExChiese.exec(lis[this.count].innerHTML)[0];
                AddressArea._m.addClass('hide',this.ul);
                AddressArea._m.addClass('hide',this.ul);
                /* IE6 */
                AddressArea._m.addClass('hide',this.myIframe);
                break;
            default:
                break;
        }
    },

    /* *
     * 下拉列表的li事件
     * @ liEvent
     * */
    liEvent:function(){
        var that = this;
        var lis = AddressArea._m.$('li',this.ul);
        for(var i = 0,n = lis.length;i < n;i++){
            AddressArea._m.on(lis[i],'click',function(event){
                event = AddressArea._m.getEvent(event);
                var target = AddressArea._m.getTarget(event);
                
                //获得li中html
                var tmp = target.innerHTML;
                
                //获地点ID
            	that.addressId.value = tmp.split('name="')[1].split('"')[0];
            	
            	//获得地点名字
            	var addressName = tmp.split('>')[1].split('<')[0];
            	that.input.value = addressName;
            	
                AddressArea._m.addClass('hide',that.ul);
                /* IE6 下拉菜单点击事件 */
                AddressArea._m.addClass('hide',that.myIframe);
            });
            AddressArea._m.on(lis[i],'mouseover',function(event){
                event = AddressArea._m.getEvent(event);
                var target = AddressArea._m.getTarget(event);
                AddressArea._m.addClass('on',target);
            });
            AddressArea._m.on(lis[i],'mouseout',function(event){
                event = AddressArea._m.getEvent(event);
                var target = AddressArea._m.getTarget(event);
                AddressArea._m.removeClass('on',target);
            });
        }
    }
};